import PropTypes from 'prop-types';
import React, { ReactChild, ReactElement } from 'react';

import classNames from 'classnames';

import { IDOMProps } from '../../utils/props';

import { AccordionPanel, IAccordionPanelProps } from './AccordionPanel';

export interface IAccordionProps extends IDOMProps {
  className?: string;
  style?: React.CSSProperties;
  onToggle?: (index: number) => void;
  children: React.ReactElement<AccordionPanel> | Array<React.ReactElement<AccordionPanel>>;
}

export class Accordion extends React.Component<IAccordionProps, {}> {
  public static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    style: PropTypes.object,
  };

  public static defaultProps = {
    className: '',
    style: {},
  };

  public static Panel: typeof AccordionPanel;

  constructor(props: IAccordionProps) {
    super(props);
  }

  public render() {
    const { className, style, onToggle, ...domProps } = this.props;
    return (
      <div
        {...domProps as IDOMProps}
        className={classNames('br-accordion', className)}
        style={style}
      >
        {
          React.Children.map<ReactElement<IAccordionPanelProps>>(
            this.props.children, (child: ReactChild, index: number) => {
              const ele = child as ReactElement<IAccordionPanelProps>;
              return React.cloneElement(ele, {
                index,
                onToggle,
              });
            })
        }
      </div>
    );
  }
}

Accordion.Panel = AccordionPanel;
